html
<!DOCTYPE html>
<html>
<head>
  <title>表单请求示例</title>
</head>
<body>
  <form id="myForm">
    <input type="text" name="username" placeholder="用户名" required>
    <input type="email" name="email" placeholder="邮箱" required>
    <button type="submit">提交</button>
  </form>

  <div>
    <button onclick="sendGetRequest()">发送 GET 请求</button>
    <button onclick="sendPostRequest()">发送 POST 请求</button>
  </div>

  <script>
    const form = document.getElementById('myForm');
    
    // 表单提交事件
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      
      const formData = new FormData(form);
      const data = Object.fromEntries(formData);
      
      // 使用 POST 请求提交表单
      await postRequest(data);
    });

    // GET 请求示例
    async function sendGetRequest() {
      const response = await fetch('/api/users?action=list');
      const users = await response.json();
      console.log('GET 响应:', users);
    }

    // POST 请求示例
    async function sendPostRequest() {
      const data = {
        username: 'testuser',
        email: 'test@example.com'
      };
      
      const response = await fetch('/api/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
      });
      
      const result = await response.json();
      console.log('POST 响应:', result);
    }

    // 通用的 POST 请求函数
    async function postRequest(data) {
      try {
        const response = await fetch('/api/submit', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        alert('提交成功: ' + JSON.stringify(result));
        form.reset();
      } catch (error) {
        console.error('提交失败:', error);
        alert('提交失败，请重试');
      }
    }
  </script>
</body>
</html>